//
//  LJHSearchListViewController.m
//  HEARME
//
//  Created by mac on 16/2/25.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LJHSearchListViewController.h"
#import "LJHSearchModel.h"
#import "LJHSearchResultTableView.h"
#import "LJHAlbumListTableViewCell.h"
#import "LJHAlbumsDetailCell.h"
#import "LJHAlbumsDetailViewController.h"
@interface LJHSearchListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate>

@property (nonatomic,retain)LJHBaseTableView *myTableView;
@property (nonatomic,retain)NSMutableArray *myArray;
@property (nonatomic,retain)UISearchBar *mySearchBar;
@property (nonatomic,retain)UISearchController *searchController;
@property (nonatomic,retain)UIView *myView;
@property (nonatomic,retain)LJHSearchResultTableView *searchResultTableView;
@property (nonatomic,retain)UINavigationController *naVC;
@property (nonatomic,retain)LJHAlbumsDetailCell *albumDetailVC;
@property(nonatomic,assign)CGFloat cellHeight;
@property (nonatomic, retain) NSMutableArray *albumArray;
@property (nonatomic ,retain) NSMutableArray *trackArray;
@property (nonatomic, retain) UIView *btnView;
@property (nonatomic,retain)NSMutableArray *arrBtns;
@property (nonatomic,retain)NSMutableArray *btnArr;

@end

@implementation LJHSearchListViewController
- (void)dealloc
{
    
    [_btnView release];
    [_albumArray release];
    [_trackArray release];
    [_myView release];
    [_searchController release];
    [_myArray release];
    [_mySearchBar release];
    [_myTableView release];
    [super dealloc];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
//    [self.view bringSubviewToFront:self.messageView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSearchBar];
    [self createTableView];
    
    LJHBaseButton * backButton = [LJHBaseButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0 , 20, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"btn_back_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_h@2x.png"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.tabBarController.tabBar.hidden = YES;
    // Do any additional setup after loading the view.
}
#pragma mark - 返回按钮方法
-(void)backButtonAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - 创建searchBar
-(void)createSearchBar
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = @"搜索声音、专辑...";
    self.searchController.searchBar.tintColor = [UIColor redColor];
    self.searchController.searchBar.delegate = self;
    //    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
    //    [self.view addSubview:self.myView];
    //    [_myView release];
    
    //    [self.myView addSubview:self.searchController.searchBar];
    self.navigationItem.titleView = self.searchController.searchBar;
    
}

#pragma mark - 点击取消按钮触发方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self getMoreData:searchBar.text];
    [self.view bringSubviewToFront:self.searchResultTableView];
    
    
}

#pragma mark - 创建tableView
-(void)createTableView
{
    //搜索tableView
    self.myTableView = [[LJHBaseTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.myTableView registerClass:[LJHBaseTableViewCell class] forCellReuseIdentifier:@"searchCell"];
    self.myTableView.bounces = NO;//禁止拖动
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
//    headView.backgroundColor = [UIColor whiteColor];
    
    //搜索结果tableView
    self.searchResultTableView = [[LJHSearchResultTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
//    self.searchResultTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.searchResultTableView];
    [_myTableView release];
    self.searchResultTableView.dataSource = self;
    self.searchResultTableView.delegate = self;
    [self.searchResultTableView registerClass:[LJHAlbumsDetailCell class] forCellReuseIdentifier:@"searchTrackCell"];
    [self.searchResultTableView registerClass:[LJHAlbumListTableViewCell class] forCellReuseIdentifier:@"searchAlbumCell"];
    self.searchResultTableView.bounces = NO;
    
    self.btnView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.btnView.backgroundColor = [UIColor clearColor];
    [self.myTableView addSubview:self.btnView];
//    [_myLabel release];
    [self createButtons];
    //先让搜索的tableView在前面
    [self.view bringSubviewToFront:self.myTableView];
}
-(void)createButtons
{
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 130, 80, 30)];
    lable.text = @"热门搜索";
    lable.backgroundColor = [UIColor clearColor];
    lable.textColor = [UIColor grayColor];
    [self.btnView addSubview:lable];
    
    [LJHAppTools afnGetRequest:@"http://mobile.ximalaya.com/m/hot_search_keys?device=iPhone" block:^(id result) {
        NSDictionary *dic = result;
        self.btnArr= [dic objectForKey:@"keys"];
        NSArray *newBtnArr = [self.btnArr subarrayWithRange:NSMakeRange(0, 9)];
        for (int i = 0; i<3; i++) {
            for (int j = 0; j<3; j++){
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(i%3*((WIDTH-20*4)/3+20)+20,60 + j%3*(30+10)+110, (WIDTH-20*4)/3, 30);
                btn.tag = i*3+j;
                [btn setTitle:[newBtnArr objectAtIndex:i*3+j] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [btn.layer setMasksToBounds:YES];
                [btn.layer setCornerRadius:12.0]; //设置矩形四个圆角半径
                [btn.layer setBorderWidth:1.0]; //边框宽度
                [btn addTarget:self action:@selector(btnSeaAction:) forControlEvents:UIControlEventTouchUpInside];
                CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
                CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });
                [btn.layer setBorderColor:colorref];//边框颜色
                [self.btnView addSubview:btn];
                [self.arrBtns addObject:btn];
                
            }
        }
        
        
    } error:^(NSError *error) {
        
        
    }];
    
}

-(void)btnSeaAction:(UIButton *)btn
{
    
    self.searchController.searchBar.text = btn.titleLabel.text;
    NSLog(@"%@",btn.titleLabel.text);
    
//    NSString *str = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=iphone&core=all&kw=hh&page=1&rows=3&spellchecker=true"];
//    
//    [LJHAppTools afnGetRequest:str block:^(id result) {
//        self.albumArray = [NSMutableArray array];
//        self.trackArray = [NSMutableArray array];
//        NSMutableArray *albumArray = [[result objectForKey:@"album"] objectForKey:@"docs"];
//        for (NSMutableDictionary *dic in albumArray) {
//            LJHAlbumModel *model = [LJHAlbumModel modelWithDictionary:dic];
//            [self.albumArray addObject:model];
//        }
//        
//        NSMutableArray *trackArray = [[result objectForKey:@"track"] objectForKey:@"docs"];
//        for (NSMutableDictionary *dic in trackArray) {
//            LJHTrackModel *model = [LJHTrackModel modelWithDictionary:dic];
//            [self.trackArray addObject:model];
//        }
//        self.myLabel.alpha = 0;
//        //        [GiFHUD dismiss];
//        [self.searchResultTableView reloadData];
//        
//    } error:^(NSError *error) {
//        //        [GiFHUD dismiss];
//        NSLog(@"%@", error);
//    }];

    
}
#pragma mark - 请求数据
-(void)getData:(NSString *)searchString
{
    [GiFHUD setGifWithImageName:@"loading.gif"];
    [GiFHUD show];
    
    self.myArray = [NSMutableArray array];
    NSString *string = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iphone&kw=%@", searchString];
    [LJHAppTools afnGetRequest:string block:^(id result) {
        
        
        NSMutableArray *albumArray = [result objectForKey:@"albumResultList"];
        for (NSMutableDictionary *albumDic in albumArray) {
            LJHSearchModel *model = [LJHSearchModel modelWithDictionary:albumDic];
            [self.myArray addObject:model];
        }
        
        NSMutableArray *queryArray = [result objectForKey:@"queryResultList"];
        for (NSMutableDictionary *queryDic in queryArray) {
            
            LJHSearchModel *model = [LJHSearchModel modelWithDictionary:queryDic];
            [self.myArray addObject:model];
        }
        
        self.btnView.alpha = 0;

//        [GiFHUD dismiss];
        [self.myTableView reloadData];
    } error:^(NSError *error) {
//        [GiFHUD dismiss];
        NSLog(@"数据请求失败 error");
    }];
}
#pragma mark - 请求点击cell搜索的数据
-(void)getMoreData:(NSString *)cellString
{

    NSString *str = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=iphone&core=all&kw=%@&page=1&rows=3&spellchecker=true",cellString];
    
    [LJHAppTools afnGetRequest:str block:^(id result) {
        self.albumArray = [NSMutableArray array];
        self.trackArray = [NSMutableArray array];
        NSMutableArray *albumArray = [[result objectForKey:@"album"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in albumArray) {
            LJHAlbumModel *model = [LJHAlbumModel modelWithDictionary:dic];
            [self.albumArray addObject:model];
        }
        
        NSMutableArray *trackArray = [[result objectForKey:@"track"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in trackArray) {
            LJHTrackModel *model = [LJHTrackModel modelWithDictionary:dic];
            [self.trackArray addObject:model];
        }
        self.btnView.alpha = 0;
//        [GiFHUD dismiss];
        [self.searchResultTableView reloadData];
        
    } error:^(NSError *error) {
//        [GiFHUD dismiss];
        NSLog(@"%@", error);
    }];
}

#pragma mark - tableView协议方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.myTableView) {
        return 1;
    }
    else{
        return 2;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.myTableView) {
        return self.myArray.count;
    }
    
    else
    {
        //        NSLog(@"%ld", self.albumArray.count);
        return self.albumArray.count;
        
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LJHAlbumListTableViewCell *albumCell = [tableView dequeueReusableCellWithIdentifier:@"searchAlbumCell"];
    LJHAlbumsDetailCell *trackCell = [tableView dequeueReusableCellWithIdentifier:@"searchTrackCell"];
    LJHBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    
    if (tableView == self.myTableView) {
        NSRange range = NSMakeRange(0, 0);
        
        LJHSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
        NSArray *strArray = [model.highlightKeyword componentsSeparatedByString:@"</em>"];
        if (strArray.count>1) {
            NSInteger length = ((NSString *)[strArray objectAtIndex:0]).length;
            range =  NSMakeRange(0, length-4);
        }
        else
        {
            range = NSMakeRange(0, 0);
        }
        
        NSMutableAttributedString *stringM = [[NSMutableAttributedString alloc] initWithString:model.keyword];
        [stringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        cell.textLabel.attributedText = stringM;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:PLACEHOLDER];
        return cell;
        
    }
    
    else  if (tableView == self.searchResultTableView && indexPath.section == 0){
        
        LJHAlbumModel *model = [self.albumArray objectAtIndex:indexPath.row];
        albumCell.albumModel = model;
        [albumCell.newsPic sd_setImageWithURL:[NSURL URLWithString:model.cover_path] placeholderImage:PLACEHOLDER];
        albumCell.contentCount.text = [NSString stringWithFormat:@"%.2f万",(CGFloat)model.play/10000];
        [albumCell.contentCount sizeToFit];
        albumCell.duration.text = [NSString stringWithFormat:@"%ld集", (long)model.tracks];
        [albumCell.duration sizeToFit];
        return albumCell;
    }
    else
    {
        LJHTrackModel *model = [self.trackArray objectAtIndex:indexPath.row];
        trackCell.trackModel = model;
        [trackCell.trackPic sd_setImageWithURL:[NSURL URLWithString:model.cover_path] placeholderImage:PLACEHOLDER];
        trackCell.playCount.text = [NSString stringWithFormat:@"%.2f万", (CGFloat)model.count_play/10000];
        trackCell.duration.text = [NSString stringWithFormat:@"%@人想听", model.count_like];
        self.cellHeight = trackCell.playCount.frame.origin.y + trackCell.playCount.frame.size.height + 10;
        return trackCell;
    }
    
    
    
    
}

#pragma mark - 点击cell方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.myTableView) {
        LJHSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
        [self getMoreData:model.keyword];
        self.searchController.searchBar.text = model.keyword;
        [self.view bringSubviewToFront:self.searchResultTableView];
        
    }
    else if (tableView == self.searchResultTableView&&indexPath.section == 0)
    {
        LJHAlbumsDetailViewController *albumsDetailVC = [[LJHAlbumsDetailViewController alloc] init];
        LJHAlbumModel *model = [self.albumArray objectAtIndex:indexPath.row];
        albumsDetailVC.navigationController.navigationBar.translucent = YES;
        albumsDetailVC.albumId = model.myId;
        self.navigationController.navigationBarHidden = NO;
        albumsDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:albumsDetailVC animated:YES];
    }
    else
    {
        LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
        LJHTrackModel *sing = [self.trackArray objectAtIndex:indexPath.row];
        player.song_id = sing.trackId;
        player.allMusicArray = self.trackArray;
        player.indexRow = indexPath.row;
        [self presentViewController:naVC animated:YES completion:^{
            
        }];
        
    }
    
    
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchResultTableView&&section == 0) {
        return @"专辑";
    }
    else if (tableView == self.searchResultTableView&&section == 1)
    {
        return @"声音";
    }
    
    return nil;
}



-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    [self.view bringSubviewToFront:self.myTableView];
    NSString *searchString = [self.searchController.searchBar text];
    
    
    if ([searchString isEqualToString:@""]) {
        
        
    }
    else {
        
        [self getData:searchString];
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.myTableView) {
        return HEIGHT*0.06;
    }
    else if (tableView == self.searchResultTableView&&indexPath.section == 1) {
        return self.cellHeight;
    }
    else
    {
        return WIDTH*0.3;
    }
}

//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}

//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
//    [GiFHUD dismiss];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
